package com.app.android.coliy.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import com.app.android.coliy.R;
import com.app.android.coliy.bean.LocalFileInfo;
import com.app.android.coliy.constant.SPConstants;
import com.app.android.coliy.dialog.CommInput_Dialog;
import com.app.android.coliy.event.Event_BeginPrint;
import com.app.android.coliy.event.Event_CurrentFile;
import com.app.android.coliy.event.Event_MultiFile_Print;
import com.app.android.coliy.tool.CommToast;
import com.app.android.coliy.tool.SPUtil;
import com.app.android.coliy.ui.fragment.BlueToothListFragment;
import com.app.android.coliy.ui.view.MultiStateView;
import com.app.android.coliy.util.BitmapUtil;
import com.app.android.coliy.util.ToastUtil;
import com.app.android.coliy.util.Util;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.crud.DataSupport;
import java.util.List;
import es.dmoral.toasty.Toasty;

/**
 * Created by Administrator on 2018/6/20.
 */

public class HomeActivity extends BaseActivity {

    private long mExitTime = 0;
    private static final int EXIT_TIME = 2000;


    int RequestCode_Scan;
    List<LocalFileInfo> localFileList;
    LocalFileInfo currentFileInfo;
    int canvasWidth = 0;

    MultiStateView multipleStatusView;
    LinearLayout ll_add_file, ll_file_list, ll_print, ll_canvas;
    RelativeLayout rl_canvas;
    ImageView iv_snap;
    HorizontalScrollView scrollview_canvas;
    TextView tv_click_to_create;

    BlueToothListFragment blueToothListFragment;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //保持常亮
        getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_home);
        initView();
        checkFilePermission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }


    //初始化控件
    private void initView() {
        canvasWidth = getResources().getDisplayMetrics().widthPixels - Util.dip2px(mContext, 16);

        setTitle(getResources().getString(R.string.app_name));    //设置标题
//        setLeftImgClickListener();  //设置左键返回
//        setLeftImgResouce(R.drawable.ico_scan_white);
        setRightImgClickListener(R.drawable.ico_edit_white);

        multipleStatusView = findViewById(R.id.multiplestatusView);
        multipleStatusView.setOnRetryListener(view -> {
            multipleStatusView.setViewState(MultiStateView.ViewState.LOADING);
            getData();
        });

        ll_add_file = findViewById(R.id.ll_add_file);
        ll_file_list = findViewById(R.id.ll_file_list);
        ll_print = findViewById(R.id.ll_print);
        rl_canvas = findViewById(R.id.rl_canvas);
        iv_snap = findViewById(R.id.iv_snap);
        scrollview_canvas = findViewById(R.id.scrollview_canvas);
        tv_click_to_create = findViewById(R.id.tv_click_to_create);
        ll_canvas = findViewById(R.id.ll_canvas);


        ll_add_file.setOnClickListener(this);
        ll_file_list.setOnClickListener(this);
        ll_print.setOnClickListener(this);
        iv_snap.setOnClickListener(this);
        rl_canvas.setOnClickListener(this);
        scrollview_canvas.setOnClickListener(this);
        tv_click_to_create.setOnClickListener(this);
        ll_canvas.setOnClickListener(this);

        blueToothListFragment = new BlueToothListFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.framelayout, blueToothListFragment).commitAllowingStateLoss();

//        String string = JniTool.sayHello("okok");
//        Log.d(string);
    }

    //网路请求 获取数据
    private void getData() {
        localFileList = DataSupport.findAll(LocalFileInfo.class);
        if (currentFileInfo == null) {
            if (localFileList != null && localFileList.size() > 0) {
                currentFileInfo = localFileList.get(0);
            }
        } else {
            getCurrentFile(currentFileInfo.filename);
        }

        if (currentFileInfo != null) {
            try {
                Bitmap bitmap = BitmapUtil.getSmallBitmap(currentFileInfo.snapshot);
                iv_snap.setImageBitmap(bitmap);

                if (bitmap.getWidth() < canvasWidth) {
                    ll_canvas.setLayoutParams(new LinearLayout.LayoutParams(canvasWidth, LinearLayout.LayoutParams.MATCH_PARENT));
                } else {
                    ll_canvas.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            scrollview_canvas.setVisibility(View.VISIBLE);
            tv_click_to_create.setVisibility(View.GONE);
        } else {
            tv_click_to_create.setVisibility(View.VISIBLE);
            scrollview_canvas.setVisibility(View.GONE);
        }
    }

    private void getCurrentFile(String fileName) {
        if (!TextUtils.isEmpty(fileName)) {
            List<LocalFileInfo> localFileList = DataSupport.findAll(LocalFileInfo.class);
            if (localFileList != null) {
                for (int i = 0; i < localFileList.size(); i++) {
                    if (fileName.equals(localFileList.get(i).filename)) {
                        currentFileInfo = localFileList.get(i);
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - mExitTime) > EXIT_TIME) {
            Toasty.info(mContext, getString(R.string.home_press_back)).show();
            mExitTime = System.currentTimeMillis();
        }else {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
        }
    }

    //点击事件
    @Override
    public void onClick(View view) {
        Intent intent;
        int FileName_Num = SPUtil.getIntValue(mContext, SPConstants.FileName_Num, 1);
        switch (view.getId()) {
            case R.id.public_title_left_img:   //左侧扫描
                checkCameraPermission();
                break;
            case R.id.ll_add_file:     //点击新建
                CommInput_Dialog dialog = new CommInput_Dialog(mContext);
                dialog.setDefault("PKK" + Util.getSerialNumber(FileName_Num));
                dialog.setIntputCallBack(obj -> {

                    String name = (String) obj;
                    if (localFileList != null) {
                        for (int i = 0; i < localFileList.size(); i++) {
                            if (name.equals(localFileList.get(i).filename)) {
                                CommToast.showToast(mContext, getString(R.string.home_dialog_hasfile));
                                return;
                            }
                        }
                    }
                    Intent intent1 = new Intent(mContext, FileEditActivity.class);
                    intent1.putExtra("fileName", name);
                    startActivity(intent1);

                    int FileName_Num1 = SPUtil.getIntValue(mContext, SPConstants.FileName_Num, 1);
                    FileName_Num1++;
                    SPUtil.putValue(mContext, SPConstants.FileName_Num, FileName_Num1);
                });
                dialog.show();
                break;
            case R.id.ll_print:     //打印
                print();
                break;
            case R.id.ll_file_list:   //文件列表
                intent = new Intent(mContext, FileListActivity.class);
                startActivity(intent);
                break;
            case R.id.public_title_right_img:   //设置
                intent = new Intent(mContext, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_click_to_create:   //点击画布
            case R.id.iv_snap:   //点击画布
            case R.id.rl_canvas:
            case R.id.scrollview_canvas:
            case R.id.ll_canvas:
                if (currentFileInfo!=null) {
                    intent = new Intent(mContext, FileEditActivity.class);
                    intent.putExtra("fileName", currentFileInfo.filename);
                    startActivity(intent);
                } else {
                    CommInput_Dialog dialog1 = new CommInput_Dialog(mContext);
                    dialog1.setDefault("PKK" + Util.getSerialNumber(FileName_Num));
                    dialog1.setIntputCallBack(obj -> {

                        String name = (String) obj;
                        if (localFileList != null) {
                            for (int i = 0; i < localFileList.size(); i++) {
                                if (name.equals(localFileList.get(i).filename)) {
                                    CommToast.showToast(mContext, getString(R.string.home_dialog_hasfile));
                                    return;
                                }
                            }
                        }
                        Intent intent12 = new Intent(mContext, FileEditActivity.class);
                        intent12.putExtra("fileName", name);
                        startActivity(intent12);

                        int FileName_Num12 = SPUtil.getIntValue(mContext, SPConstants.FileName_Num, 1);
                        FileName_Num12++;
                        SPUtil.putValue(mContext, SPConstants.FileName_Num, FileName_Num12);
                    });
                    dialog1.show();
                }
                break;
        }
    }

    /**
     * 扫码模块
     */
    int REQUEST_PERMISSION_CAMERA = 10001;

    //检查拍照权限
    private void checkCameraPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CAMERA);
            return;
        }
        openScan();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openScan();
            } else {
                CommToast.showToast(getApplicationContext(), "权限被禁止，无法打开相机");
            }
        }
    }

    private void openScan() {
        Intent intent = new Intent(mContext, ScanCaptureActivity.class);
        startActivityForResult(intent, RequestCode_Scan);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


    int REQUEST_WRITE_EXTERNAL_STORAGE = 200;

    //检查文件权限
    private void checkFilePermission() {
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE);
        }
    }

    //点击打印
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event_BeginPrint event) {

        print();
    }

    //加载某个文件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event_CurrentFile event) {
        getCurrentFile(event.fileName);
        getData();

        print();
    }

    //批量发送文件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event_MultiFile_Print event) {
//        blueToothListFragment.printBitmap_Multi(event.localFileInfos);
    }

    private void print() {
        if (currentFileInfo == null) {
            ToastUtil.showWarning(mContext, Util.getString(R.string.home_btn_print_create));
        } else {
//            blueToothListFragment.printBitmap(currentFileInfo);
        }
    }



}
